<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { getTime } from '@/utils/time';
import { baseImgPath } from '@/utils/env';
import { useDiary } from '@/hooks/diaryHook';
import { highlightKeyword } from '@/utils/searchHighlight';
const { getDiaryList, diaryList, getWeatherUrl, parsePictures, diaryCount, getUrlList } = useDiary();


const props = defineProps({
    pageSize: {
        type: Number,
        default: 2,
    },
    searchTerm: {
        type: String,
        default: '',
    },
})


// 随笔列表
const diarys = ref<any>([]);

// 分页状态
const currentPage = ref(1);
const isLoading = ref(false);
const hasMore = ref(true);

// 加载更多文章
const loadMore = async () => {
    if (isLoading.value || !hasMore.value) return;
    isLoading.value = true;
    currentPage.value++;
    request.nowPage = currentPage.value;
    try {
        getDiaryList(request);
    } catch (error) {
        console.error('加载失败:', error);
        currentPage.value--; // 回滚页码
    } finally {
        isLoading.value = false;
    }
}

// 防抖函数
let timer: ReturnType<typeof setTimeout> | null = null;
const debounceLoadMore = () => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
        loadMore();
    }, 300);
}

const request = {
    pageSize: props.pageSize,
    nowPage: currentPage.value,
    searchTerm: props.searchTerm,
    count: true,
}

// 高亮处理函数
const getHighlightedText = (text: string, keyword: string) => {
    console.log(text, keyword);
    if (!keyword.trim()) return text;
    return highlightKeyword(text, keyword);
}

// 监听diaryList变化，更新diaryList
watch(diaryList, (newVal) => {
    diarys.value.push(...newVal);
    // 检查是否加载完所有文章
    if (diarys.value.length === diaryCount.value) {
        hasMore.value = false;
    };
    console.log('diarys', diarys.value);

})

// 监听searchTerm变化，更新请求参数
watch(() => props.searchTerm, (newVal) => {
    request.searchTerm = newVal;
    diarys.value = [];
    currentPage.value = 1;
    hasMore.value = true;
    getDiaryList(request)
})


onMounted(() => {
    getDiaryList(request);
})
</script>

<template>
    <div class="w-full max-w-[800px] mx-auto px-4 py-8">
        <!-- 日记容器 -->
        <div class="diary-container bg-white rounded-2xl shadow-lg overflow-hidden">
            <!-- 顶部装饰条 -->
            <div class="h-2 bg-gradient-to-r from-amber-400 via-orange-400 to-red-400"></div>

            <!-- 标题区域 -->
            <div class="px-8 py-6 border-b border-gray-100">
                <h1 class="text-3xl font-bold text-gray-800 mb-2">随笔随记{{diaryCount}}</h1>
                <p class="text-gray-500 text-sm">记录生活的点滴，收藏当下的感悟</p>
            </div>

            <!-- 内容区域 -->
            <div class="px-8 py-6" v-for="item in diarys" :key="item.id">
                <!-- 内容标题 -->
                <div class="mb-6">
                    <h2 class="text-2xl font-bold text-gray-800" v-html="getHighlightedText(item.title, props.searchTerm)"></h2>

                </div>
                <!-- 日期和天气 -->
                <div class="flex items-center justify-between mb-6 text-sm text-gray-500">
                    <span class="flex items-center">
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z">
                            </path>
                        </svg>
                        {{ getTime(item.created_at) }}
                    </span>
                    <span class="flex items-center">
                        <img :src="getWeatherUrl(item.weather_id)" alt="天气" class="w-5 h-5" />
                    </span>
                </div>
                <!-- 内容主体 -->
                <div class="prose prose-lg max-w-none text-gray-700 leading-relaxed">
                    <div class="indent-8 underline underline-offset-4  px-8" v-html="getHighlightedText(item.content, props.searchTerm)">
                    </div>
                    <!-- 图片 -->
                    <div v-if="item.picture" class="mt-6 relative w-full">
                        <!-- 设置固定高度容器 -->
                        <div class="relative w-full h-[220px] group">
                            <div v-for="(img, index) in parsePictures(item.picture)" :key="img.id"
                                class="absolute w-[150px] h-[200px] transition-all duration-500 ease-out" :class="[
                                    index === 0 ? 'z-30 rotate-0' : '',
                                    index === 1 ? 'z-25 rotate-3 translate-x-2 translate-y-2' : '',
                                    index === 2 ? 'z-20 rotate-6 translate-x-4 translate-y-4' : '',
                                    index === 3 ? 'z-15 rotate-9 translate-x-6 translate-y-6' : '',
                                    'group-hover:rotate-0 group-hover:translate-x-0 group-hover:translate-y-0',
                                    index === 0 ? 'group-hover:translate-x-0' : '',
                                    index === 1 ? 'group-hover:translate-x-[160px]' : '',
                                    index === 2 ? 'group-hover:translate-x-[320px]' : '',
                                    index === 3 ? 'group-hover:translate-x-[480px]' : '',
                                ]">
                                <!-- preview-teleported="true" : 将预览层直接挂载到 <body> 标签下，完全脱离原来的定位上下文 -->
                                <el-image :src="baseImgPath + '/' + img.url" alt=""
                                    class="w-full h-full object-cover rounded-lg shadow-xl border-2 border-white cursor-pointer"
                                    :zoom-rate="1.2" :max-scale="5" :min-scale="0.3"
                                    :preview-src-list="getUrlList(item.picture)" show-progress :initial-index="index"
                                    fit="cover" :preview-teleported="true" :z-index="9999" :hide-on-click-modal="false"
                                    preview-class="custom-image-preview">
                                </el-image>
                            </div>
                        </div>
                    </div>
                    <!-- 分割线 -->
                    <div v-if="item.id !== diarys[diarys.length - 1].id"
                        class="mt-8 border-t border-dashed  border-gray-300"></div>

                </div>
            </div>
            <!-- 加载更多 -->
            <div class="w-full flex justify-center items-center my-10">
                <button :disabled="isLoading || !hasMore" :class="[
                    'border-2 text-xl px-4 py-2 rounded-full cursor-pointer transition-all duration-300',
                    isLoading || !hasMore
                        ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                        : 'hover:bg-amber-500 hover:scale-105'
                ]" @click="debounceLoadMore"> {{ isLoading ? '加载中...' : hasMore ? '加载更多' : '没有更多了' }}</button>
            </div>
        </div>
        <!-- 装饰元素 -->
        <div class="mt-4 flex justify-center space-x-2">
            <div class="w-2 h-2 bg-amber-400 rounded-full"></div>
            <div class="w-2 h-2 bg-orange-400 rounded-full"></div>
            <div class="w-2 h-2 bg-red-400 rounded-full"></div>
        </div>
    </div>
</template>

<style scoped>
.diary-container {
    box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;
}

.diary-container:hover {
    box-shadow: 0 20px 40px -10px rgba(0, 0, 0, 0.15);
}

/* 自定义滚动条 */
.diary-container ::-webkit-scrollbar {
    width: 8px;
}

.diary-container ::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.diary-container ::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.diary-container ::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 文本选择样式 */
.diary-container ::selection {
    background-color: rgba(251, 191, 36, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .diary-container {
        margin: 1rem;
    }
}
</style>
